#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.basic.security.oauth2.handler;

import ${package}.basic.security.oauth2.config.YkSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;

/**
 * Description:
 *  登陆成功校验
 *
 * @author wupanhua
 * @date 2020-04-25 16:50
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Slf4j
@Component
public class AuthenticationSuccessHandlerImpl extends SimpleUrlAuthenticationSuccessHandler {

	private YkSecurityProperties ykSecurityProperties;

	private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
		    throws ServletException, IOException {
	    SavedRequest savedRequest = requestCache.getRequest(request, response);

	    if (savedRequest == null) {
		    // 无返回 生成oauth token
		    setDefaultTargetUrl(ykSecurityProperties.getSsoFromLoginSuccessDefaultPage());
		    super.onAuthenticationSuccess(request, response, authentication);
		    return;
        }
	    String targetUrlParameter = getTargetUrlParameter();
	    if (isAlwaysUseDefaultTargetUrl()
			    || (targetUrlParameter != null && StringUtils.hasText(request
			    .getParameter(targetUrlParameter)))) {
		    requestCache.removeRequest(request, response);
		    super.onAuthenticationSuccess(request, response, authentication);

		    return;
	    }

	    clearAuthenticationAttributes(request);

	    // Use the DefaultSavedRequest URL
	    String targetUrl = savedRequest.getRedirectUrl();
	    URL url = new URL(targetUrl);
	    targetUrl = url.getProtocol() + "://" + url.getHost() + ":" + (url.getPort() == -1 ? 80 : url.getPort()) + "/api/v1/auth" + url.getFile();
	    logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
	    getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }

	@Autowired
	public void setYkSecurityProperties(YkSecurityProperties ykSecurityProperties) {
		this.ykSecurityProperties = ykSecurityProperties;
    }
}
